package com.jiang.demo.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiang.demo.user.domain.User;
import com.jiang.demo.user.mapper.UserMapper;
import com.jiang.demo.user.service.UserServiceLogin;
import com.jiang.demo.user.service.impl.util.UserDetailsImpl;
import com.jiang.demo.user.service.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 基于Spring Security框架中的用户认证流程的登录系统
 */

@Service
public class UserServiceLoginImpl implements UserServiceLogin {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private UserMapper userMapper;

    @Override
    public Map<String, String> login(Map<String, String> data)  throws Exception {
        Map<String, String> map = new HashMap<>();
        String username = data.get("username");
        String password = data.get("password");
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user1 = userMapper.selectOne(queryWrapper);

        if (user1 == null) {
            map.put("error_message", "用户不存在");
            return map;
        }
        try {
            // 将前端传来的username和password进行封装成 authenticationToken
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(username, password);

            Authentication authenticate = authenticationManager.authenticate(authenticationToken);

            UserDetailsImpl loginUser = (UserDetailsImpl) authenticate.getPrincipal();
            User user = loginUser.getUser();
            // 设置令牌
            String jwt = JwtUtil.createJWT(user.getId().toString());
//            System.out.println(jwt);

            map.put("error_message", "success");
            map.put("token", jwt);
        } catch (AuthenticationException e) {
            // 捕获认证异常，并设置密码错误的信息
            map.put("error_message", "密码错误");
        }
        return map;
    }
}
